package com.hwbsite.hwbback.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hwbsite.hwbback.consstants.CommonConstants;
import com.hwbsite.hwbback.consstants.ResConstant;
import com.hwbsite.hwbback.entity.*;
import com.hwbsite.hwbback.mapper.UserInfoMapper;
import com.hwbsite.hwbback.mapper.WbFileMapper;
import com.hwbsite.hwbback.mapper.WbGoodJobMapper;
import com.hwbsite.hwbback.mapper.WbInfoMapper;
import com.hwbsite.hwbback.utils.DhRes;
import com.hwbsite.hwbback.utils.FileUploader;
import com.hwbsite.hwbback.utils.UserTokenUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
@AllArgsConstructor
public class WeiboServiceImpl implements WeiboService{
    private final WbInfoMapper wbInfoMapper;
    private final WbFileMapper wbFileMapper;
    private final FileUploader uploader;
    private final UserInfoMapper userMapper;
    private final WbGoodJobMapper wbGoodJobMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DhRes saveWB(WeiboPublishDTO dto) throws Exception {
        String wbId = UUID.randomUUID().toString();

        WbInfo wbInfo = new WbInfo();
        wbInfo.setId(wbId);
        wbInfo.setUserId(UserTokenUtils.getUserId().getUserId());
        wbInfo.setWbContent(dto.getContent());
        wbInfo.setIsCompleted(!dto.isHasFile());

        wbInfoMapper.insert(wbInfo);

        return DhRes.success(wbId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DhRes saveWBFile(WeiboPublishDTO dto) throws Exception{
        WbInfo wbInfo = wbInfoMapper.selectById(dto.getId());
        if (wbInfo == null){
            return DhRes.fail(ResConstant.SYSTEM_ERROR_CODE);
        }

        if(dto.getFile() != null ){
            String path = CommonConstants.WB_IMG_PATH  + LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE) +  "/";

            boolean t = dto.getType() == 1 ? true: false;

            List<UploaderRES> res = new ArrayList<>();
            if(t){
                    res = uploader.uploade(dto.getFile(), path , true, dto.getOrder());
            }else {
                    res = uploader.uploade(dto.getFile(), path , false, dto.getOrder());
            }
            res.forEach(e->{
                WbFile wbFile = new WbFile();
                wbFile.setFileId(e.getId());
                wbFile.setWbId(dto.getId());
                wbFile.setOrderNo(e.getOrderNo());
                wbFile.setThumbnail(e.isThumbnail());
                wbFile.setFileType(dto.getType());
                wbFileMapper.insert(wbFile);
            });
        }else {

        }

        wbInfo.setIsCompleted(true);
        wbInfoMapper.updateById(wbInfo);
        return DhRes.success(dto.getOrder());
    }

    @Override
    public IPage<WbResult> getWb(Page page,WeiboPublishDTO dto) {
        List<WbResult> wbResults = new ArrayList<>();
       LambdaQueryWrapper<WbInfo> query = Wrappers.<WbInfo>lambdaQuery()
                .eq(WbInfo::getIsDeleted, false).eq(WbInfo::getIsCompleted, true);
       if(StrUtil.isNotBlank(dto.getContent())){
           query.like(WbInfo::getWbContent, dto.getContent());
       }

        if(dto.getStartTime() != null && dto.getEndTime() != null){

            query.between(WbInfo::getCreateTime, dto.getStartTime(), dto.getEndTime());
        }

        if(StrUtil.isNotBlank(dto.getId())){
            query.eq(WbInfo::getId, dto.getId());
        }


        query.orderByDesc(WbInfo::getCreateTime);

        Page  pageWb = wbInfoMapper.selectPage( page, query);
        List<WbInfo> wbInfos = pageWb.getRecords();
        wbInfos.forEach(e->{
            WbResult wbResult = new WbResult();
            wbResult.setWbInfo(e);
            UserInfo userInfo =userMapper.selectById(e.getUserId());
            userInfo.setPassword(null);
            wbResult.setUserInfo(userInfo);

            wbResult.setWbFileAll(WbFileAll.builder()
                    .images( wbFileMapper.selectFileInfo(e.getId(), 0 , 1))
                    .thumbnail(wbFileMapper.selectFileInfo(e.getId(), 1 , 1))
                    .videos(wbFileMapper.selectFileInfo(e.getId(), 0 , 2))
                    .build());

            wbResult.setWbGooJobRes(getWbGJ(e.getId()));

            wbResults.add(wbResult);
        });
        pageWb.setRecords(wbResults);
        return pageWb;
    }

    @Override
    public WbGooJobRes getWbGJ(String wbId){

        List<WbGoodJob>  wbGoodJobs =  wbGoodJobMapper.selectList(Wrappers.<WbGoodJob>lambdaQuery().eq(WbGoodJob::getWbId, wbId));

        return WbGooJobRes.builder()
                .wbGJN(CollUtil.isNotEmpty(wbGoodJobs) ? wbGoodJobs.size() :0)
                .ownDo(wbGoodJobs.stream().anyMatch(e-> UserTokenUtils.getUser().getUserId().equals(e.getUserId())))
                .build();
    }



    @Override
    public DhRes goodJob(String wbId) {
        WbGoodJob wbGoodJob = new WbGoodJob();
        List<WbGoodJob> list = wbGoodJobMapper.selectList(
                Wrappers.<WbGoodJob>lambdaQuery().eq(WbGoodJob::getWbId, wbId)
                        .eq(WbGoodJob::getUserId, UserTokenUtils.getUser().getUserId())
                );
        if(CollUtil.isNotEmpty(list)){
            wbGoodJob = list.get(0);
            wbGoodJob.setIsDo(!wbGoodJob.getIsDo());
            wbGoodJobMapper.updateById(wbGoodJob);
        }else {

            wbGoodJob.setWbId(wbId);
            wbGoodJob.setUserId(UserTokenUtils.getUser().getUserId());
            wbGoodJobMapper.insert(wbGoodJob);
        }
        return DhRes.success(getWbGJ(wbId));
    }

    @Override
    public DhRes deleteWB(String id) {
        wbInfoMapper.deleteById(id);
        return DhRes.success();
    }


    @Override
    public DhRes comment(WbReplyDTO wbReplyDTO) {
        return DhRes.success();
    }

    @Override
    public DhRes getWbC(WeiboPublishDTO dto) {
        WbInfo wbInfo =  wbInfoMapper.selectById(dto.getId());
        return null;
    }


}
